/*  ----------------------------------------------------------------------------
 *  Arello Mobile
 *  Fast 3d Engine
 *  ----------------------------------------------------------------------------
 * Except where otherwise noted, this work is licensed under
 * http://creativecommons.org/licenses/by/3.0
 */

#include "Dialog.h"
#include <xml/Stream.h>

namespace liba
{
namespace lib2d
{
namespace gui
{

namespace dialog
{
CloseButton::CloseButton( Dialog * parent )
:	Button( parent ),
	parent( parent )
{}

void CloseButton::on_button_up( const Vector2 & point, const Atom & button_name )
{
	if( is_pressed() )
	{
		parent->on_close();
		return;
	}
	return Button::on_button_up( point, button_name );
}

void CloseButton::layout()
{
	window_rect.x = get_parent()->get_window_rect().width - view->get_width() - 6;
	window_rect.width = view->get_width();
	window_rect.y = 4;
	window_rect.height = view->get_height();
}

}

Dialog::Dialog( Object * parent )
:	Object( parent ),
	mouse_catched( false )
{
	window_rect = Rect( 250, 150, 200, 200 );

	close_button = new dialog::CloseButton( this );

	view = new view::Dialog( this );
	AutoPtr< resource::Resource > res = resource::Manager::create_resource( "dialog.xml" );
	xml::StreamResource( res ).load( &xml::Root( view, "DialogData" ) );

	close_button->layout();
}

void Dialog::on_close()
{
	//TODO :)
	delete this;
}

bool Dialog::on_attribute( xml::Provider * prov, const std::string & name, const std::string & value )
{
	return false;
}

bool Dialog::on_node( xml::Provider * prov, const std::string & name )
{
	return false;
}

void Dialog::on_button_down( const Vector2 & point, const Atom & button_name )
{
	Rect caption( get_window_rect() );
	caption.x = 0;
	caption.y = 0;
	caption.height = view->get_margins().top();
	if( caption.is_intersects( point ) && !close_button->get_window_rect().is_intersects( point ) )
	{
		mouse_pos = point;
		mouse_catched = true;
	}

	Object::on_button_down( point, button_name );
}

void Dialog::on_button_up( const Vector2 & point, const Atom & button_name )
{
	mouse_catched = false;
	Object::on_button_up( point, button_name );
}

void Dialog::track_mouse_move( const Vector2 & point )
{
	if( mouse_catched )
	{
		window_rect.x += point.x() - mouse_pos.x();
		window_rect.y += point.y() - mouse_pos.y();
//		mouse_pos = point;
	}
}

void Dialog::on_mouse_move_outside( const Vector2 & point )
{
	track_mouse_move( point );
	Object::on_mouse_move_outside( point );
}

void Dialog::on_mouse_move( const Vector2 & point )
{
	track_mouse_move( point );
	Object::on_mouse_move( point );
}

} //namespace gui
} //namespace lib2d
} //namespace liba

